<template>
  <div class="file-upload">
    <h2>Upload File</h2>
    <el-upload
        :action="uploadUrl"
        :before-upload="beforeUpload"
        :on-success="handleSuccess"
        :on-error="handleError"
        :data="{file_name:uploadData.file_name}"
        :headers="header"
    >
      <el-button type="primary">Select File</el-button>
    </el-upload>
  </div>
</template>

<script>
import {ElMessage} from 'element-plus'
import axios from 'axios'
import {eventBus} from '@/eventBus.js';

export default {
  name: 'FileUpload',
  data() {
    return {
      uploadData: {}
    }
  },
  computed: {
    uploadUrl() {
      return `${axios.defaults.baseURL}/upload`
    },
    header() {
      return {Authorization: `Bearer ${localStorage.getItem('accessToken')}`}
    }

  },
  methods: {
    async beforeUpload(file) {
      this.uploadData = {
        file_name: file.name,
        file_size: file.size
      }
      try {
        const response = await axios.post("/apply_for_upload", this.uploadData, {
          headers: this.header
        })
        if (response.data.success) {
          return true
        } else {
          ElMessage.error(response.data.message)
          return false
        }
      } catch (error) {
        ElMessage.error('Failed to apply for upload')
        return false
      }
    },
    handleSuccess(response) {
      if (response.success) {
        ElMessage.success('File uploaded successfully')
        eventBus.emit('file uploaded');
      } else {
        ElMessage.error(response.message)
      }
    },
    handleError() {
      ElMessage.error('Failed to upload file')
    }
  }
}
</script>

<style scoped>
.file-upload {
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
</style>